//console.log('in nslUtils')
/**
 * 克隆一个对象
 * @param {boolean} deep 是否深度克隆
 */
export const clone = function (obj: any, deep: boolean) {
    if (Array.isArray(obj)) {
        if (deep) {
            //深度克隆
            var newArr:any = [] ;
            for (var i = 0; i < obj.length; i++) {
                newArr.push(clone(obj[i] , deep));
            }
            return newArr;
        }
        else {
            return obj.slice(); //复制数组
        }
    }
    else if (typeof obj === "object") {
        var newObj :any= {};
        for (var prop in obj) {
            if (deep) {
                //深度克隆
                newObj[prop] = clone(obj[prop], deep);
            }
            else {
                newObj[prop] = obj[prop];
            }
        }
        return newObj;
    }
    else {
        //函数、原始类型
        return obj; //递归的终止条件
    }
}

/**
 * @param {string} path
 * @returns {Boolean}
 */
export function isExternal(path: string) {
    const isExternal = /^(https?:|http?:|mailto:|tel:)/.test(path);
    return isExternal;
}

function mapToJson(map:Map<string,any>) {
    var obj = Object.create(null);
    //@ts-expect-error
    map.keys().forEach((key:string)=>{
        obj[key] = map.get(key);
    });
    return JSON.stringify(obj);
}

function toNumber(str:string|undefined|null):number{
    if(str === undefined || str === null ){
        return 0
    }
    if(str.trim() === ''){
        return 0;
    }
    if(str.includes('.')){
        return parseFloat(str);
    }else{
        return parseInt(str);
    }
}

function toInt(str:string|undefined|null):number{
    if(str === undefined || str === null ){
        return 0
    }
    if(str.trim() === ''){
        return 0;
    }
    return parseInt(str)
}

function toFloat(str:string|undefined|null):number{
    if(str === undefined || str === null ){
        return 0
    }
    if(str.trim() === ''){
        return 0;
    }
    return parseFloat(str)
}


const NslUtils={
    clone,
    isExternal,
    mapToJson,
    toNumber,
    toInt,
    toFloat
}
export {NslUtils,mapToJson}